package top.kaoshanji.p1ch05a;

import org.apache.hc.core5.http.ContentType;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * 代码清单-p1ch05a-162页a：动态创建状态码错误页
 * 代码清单-p1ch05a-169页a：动态创建通用目的错误页
 * URL访问地址：/errorDisplay
 * @author kaoshanji
 * ^_^
 * create time 2025/4/4 15:46
 */
public class ErrorDisplay extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求对象的编码
        req.setCharacterEncoding(StandardCharsets.UTF_8.name());

        // 设置响应对象的编码和内容格式
        resp.setContentType(ContentType.TEXT_HTML.toString());
        PrintWriter out = resp.getWriter();

        String code = null, message = null, type = null;

        Object codeObj = req.getAttribute("javax.servlet.error.status_code");
        Object messageObj = req.getAttribute("javax.servlet.error.message");
        Object typeObj = req.getAttribute("javax.servlet.error.exception_type");

        if (codeObj != null) {
            code = codeObj.toString();
        }
        if (messageObj != null) {
            message = messageObj.toString();
        }
        if (typeObj != null) {
            type = typeObj.toString();
        }

        String reason = (code != null ? code : type);

        out.println("<HTML>");
        out.println("<HEAD><TITLE>" + reason + ": " + message + "</TITLE></HEAD>");
        out.println("<BODY>");
        out.println("<H1>" + reason + "</H1>");
        out.println("<H2>" + message + "</H2>");
        out.println("<HR>");
        out.println("<I>Error accessing " + req.getRequestURI() + "</I>");
        out.println("</BODY></HTML>");

    }


}
